<?php
/**
 * 
 * @author zhouming
 *
 */
class Order_model extends MY_Model {
    public function __construct() {
            parent::__construct ();
    }
    public function init(){}
    /**
     * 更新订单数据
     * @param unknown $orderId
     * @param unknown $data
     * @return boolean
     */
    public function updateOrder($orderId , $data){
    	$result = false;
    	if($orderId > 0){
    		$result = $this->db->where(array('id'=>$orderId))->update('dwf_order', $data);
    	}
    	return $result;
    }
    /**
     * 添加订单完成记录
     * @param unknown $order_id
     * @param unknown $user_id
     * @param unknown $user_type 操作人身份 1客户 2 区域经理 3 系统管理员
     * @return unknown
     */
    public function addOrderCompletedRecord($order_id,$user_id,$user_type){
        $result = false;
        $data = array(
            'order_id'=>$order_id,
            'operator'=>$user_id,
            'operator_type'=>$user_type, //操作人身份 1客户 2 区域经理 3 系统管理员
            'account_for_commpany'=>0,
            'account_for_recommender'=>0,
            'operat_time'=>date('Y-m-d H:i:s')
        );
        $result = $this->db->insert('dwf_order_completed',$data);
        return $result;
    }
    /**
     * 
     * 添加订单取消记录
     * @param unknown $order_id
     * @param unknown $user_id
     * @param unknown $user_type 操作人身份 1客户 2 区域经理 3 系统管理员
     * @param unknown $remark 取消说明
     * @return unknown
     */
    public function addOrderCancelledRecord($order_id,$user_id,$user_type , $remark){
        $result = false;
        $data = array(
            'order_id'=>$order_id,
            'amount_returned'=>0,
            'operator'=>$user_id,
            'operator_type'=>$user_type, //操作人身份 1客户 2 区域经理 3 系统管理员
            'operat_time'=>date('Y-m-d H:i:s'),
            'remark'=>$remark
        );
        $stockRecord = $this->unreleaseStockList($order_id);
        if(!empty($stockRecord)){
            $this->releaseStock($stockRecord);
        }
        $result = $this->db->insert('dwf_order_cancelled',$data);
        return $result;
    }
    /**
     * 更新订单数据
     * @param unknown $orderNum
     * @param unknown $data
     * @return boolean
     */
    public function updateOrderByOrderNum($orderNum , $data){
    	$result = false;
    	if($orderNum > 0){
    		$result = $this->db->where(array('order_num'=>$orderNum))->update('dwf_order', $data);
    	}
    	return $result;
    }

    /**
     * 查询订单中商品库存去向列表
     * @param $order_id 订单ID
     * @return bool|void
     */
    public function unreleaseStockList($order_id){
        $stockRecord = $this->db->select('id, goods_id, num, real_num')
            ->from('dwf_delivery_record')
            ->where(
                array(
                    'status' => 0,
                    'order_id' => $order_id
                )
            )
            ->get()->result_array();
        return $stockRecord;
    }

    /**
     * 释放库存
     * @param array $stockList
     * @return bool|void
     */
    public function releaseStock($stockList = array()){
        if(!is_array($stockList) || empty($stockList))
            return;
        $result = false;
        foreach($stockList as $key => $value){
            $this->db->set('store_nums_real', 'store_nums_real +'. $value['real_num'], false);
            $this->db->set('store_nums', 'store_nums +'. $value['num'], false);
            $this->db->set('sell_count', 'sell_count -'. ($value['num'] + $value['real_num']), false);
            $result = $this->db->where('id', $value['goods_id'])->update('dwf_product_goods');
            $this->db->where('id', $value['id'])->update('dwf_delivery_record', array('status' => '1'));
        }
        return $result;
    }

    /**
     * 
     * @param unknown $userId
     * @param unknown $page
     * @param number $limit
     * @param array $status
     */
    public function getOrderList($param, $page = 1 , $limit = 10 ){
        $orderList = array();
//         print_r($param);exit;
        isset($param['manager_id']) && $this->db->where('manager_id' , $param['manager_id']);
        isset($param['start_date']) && $param['start_date'] != '' && $this->db->where('deliver_time >=' , $param['start_date'] . " 00:00:00");
        isset($param['end_date']) && $param['end_date'] != '' && $this->db->where('deliver_time <=' , $param['end_date'] . " 23:59:59");
        isset($param['state']) && $this->db->where('status' , $param['state']);
        isset($param['order_id']) && $this->db->like('order_num', $param['order_id'], 'before');
        $order_num =  $this->db->count_all_results('`dwf_order`',FALSE);
        
//      echo $this->db->last_query();exit;
        $this->db->select("`id`,`order_num`,`user_id`,`manager_id`,`area_id`,`order_time`,`deliver_time`,`receiving`,`remark`,`address`,`phone`,`tel`,`total`,`delivery_fee`,`pay_way`,`real_pay`,`status` ,`order_source`");
        $start = ($page-1) * $limit;
        $this->db->limit($limit, $start);
        $this->db->order_by('id', 'ASC');
        $orderList['list'] = $this->db->get()->result_array();
//         echo $this->db->last_query();exit;
        $orderList['total_page'] = ceil($order_num/$limit);
        $orderList['total_num'] = $order_num;
        return $orderList;
    }
    /**
     * 获取订单商品信息
     * @param unknown $orderId
     * @return boolean|string
     */
    public function getOrderProducts($orderId){
        $productInfo = array();
        if($orderId > 0){
        	$sql = "SELECT a.* ,b.product_image FROM dwf_order_product  AS a  LEFT JOIN dwf_product  AS b ON (a.product_id = b.id)   WHERE a.order_id = ?;";
            $binds = array('order_id'=>$orderId);
            $products = $this->queryAll($sql,$binds);
            if(!empty($products)){
            	$productInfo['products'] = $products;
            	$productInfo['total_num'] = 0;
            	foreach($products as $key=>$value){
            		$productInfo['total_num'] += $value['product_num'];
            		$productInfo['products'][$key]['product_image'] = $this->config->item('product_img_host') . $value['product_image'];
            	}
            }
        }
        return $productInfo;
        
    }
    /**
     * 订单号获取订单信息
     * @param unknown $orderNumber
     */
    public function getOrderInfoByNumber($orderNumber){
    	$orderInfo = array();
    	if($orderNumber > 0){
    		$orderInfo = $this->db->select("`id`,`order_num`,`user_id`,`manager_id`,`area_id`,`order_time`,`deliver_time`,`receiving`,`remark`,`address`,`phone`,`tel`,`total`,`delivery_fee`,`pay_way`,`real_pay`,`status` ,`order_source`")
			    		->from("dwf_order")
			    		->where('order_num',$orderNumber)
			    		->get()
			    		->row_array();
    	}
//     	echo $this->db->last_query();exit;
    	return $orderInfo;
    }
    /**
     * id获取订单信息
     * @param unknown $orderNumber
     */
    public function getOrderInfoById($orderId){
    	$orderInfo = array();
    	if($orderId > 0){
    		$orderInfo = $this->db->select("`id`,`order_num`,`user_id`,`manager_id`,`area_id`,`order_time`,`deliver_time`,`receiving`,`remark`,`address`,`phone`,`tel`,`total`,`delivery_fee`,`pay_way`,`real_pay`,`status` ,`order_source`")
    		->from("dwf_order")
    		->where('id',$orderId)
    		->get()
    		->row_array();
    	}
    	return $orderInfo;
    }
    /**
     * 获取订单支付记录
     * @param unknown $orderId
     */
    public function getOrderPayRecoder($orderId){
    	$payRecoder = array();
    	if(is_numeric($orderId)&& $orderId > 0){
    		$payRecoder = $this->db->where('order_id',$orderId)->get('dwf_pay_recorder')->result_array();
    	}elseif(is_array($orderId) && !empty($orderId)){
    	    $payRecoder = $this->db->where_in('order_id',$orderId)->get('dwf_pay_recorder')->result_array();
    	}
    	return $payRecoder;
    }
    /**
     * 发放推荐者提成
     * @param unknown $orderId
     */
    public function handedOutCommission($orderId){
    	if($orderId > 0){
    		//error_reporting(E_ALL);
    		$this->load->model('user_model');
    		
    		$orderInfo = $this->getOrderInfoById($orderId);
    		
//     		$isFirstOrder = $this->isFirstOrder($orderInfo['user_id']);
    		$isFirstOrder =false;
    		
    		$recommendInfo = $this->user_model->getUserRecommend($orderInfo['user_id'],0,1);
    		
    		$commissionFee = $this->getOrderMemberCommissionFee($orderId);
    		
//     		$commission_level_first = $orderInfo['total'] *  0.1;//首次下单10%提成
    		$commission_level_1 = $commissionFee ;//计算各级提成
    		$commission_level_2 = bcdiv($commissionFee, 5,2);
    		$commission_level_3 = bcdiv($commissionFee, 10,2);
    		$commission = array($commission_level_1 , $commission_level_2 , $commission_level_3);
    		$managerUserId = array(69309,42192,46136,38564,41232,23279,1294,4811,339,8380);
    		if(!empty($recommendInfo)){
    			foreach($recommendInfo as $key=>$value){
    				if($value['type'] == 'user'){
//     				    if(in_array($value['recommend_id'], $managerUserId)){
    				        $this->handedOutUserCommission($value['recommend_id'], $commission[$key], $orderId, $value['level']);
//     				    }
    					
//     					if($isFirstOrder && $key == 0){
//     						$this->handedOutUserCommission($value['recommend_id'], $commission_level_first, $orderId, 0);
//     					}else{
//     						$this->handedOutUserCommission($value['recommend_id'], $commission[$key], $orderId, $value['level']);
//     					}
    					
    				}elseif($value['type'] == 'shop'){
//     				    continue;
    					$this->handedOutShopCommission($value['recommend_id'], $commission[$key], $orderId, $value['level']);
//     					if($isFirstOrder && $key == 0){
//     						$this->handedOutShopCommission($value['recommend_id'], $commission_level_first, $orderId, 0);
//     					}else{
//     						$this->handedOutShopCommission($value['recommend_id'], $commission[$key], $orderId, $value['level']);
//     					}
    				}
    			}
    		}
    		$this->updateAccountdForRecommenderOrderStatus($orderId);
    	}
    	
    }
    /**
     * 获取订单会员提成总额
     * @param unknown $orderId
     * @return number
     */
    public function getOrderMemberCommissionFee($orderId){
        $fee = 0;
        if($orderId > 0){
            $product = $this->db->select('product_num,member_proportion')->where('order_id',$orderId)->get('dwf_order_product')->result_array();
            foreach($product as $value){
                $fee = bcadd($fee, bcmul($value['product_num'],$value['member_proportion'],2),2);
            }
        }
        return $fee;
    }
    /**
     * 发放用户推荐提成
     * @param unknown $userId
     * @param unknown $amount
     * @param unknown $orderNum
     * @param unknown $level
     */
    private function handedOutUserCommission($userId , $amount , $orderNum ,$level){
    	$result =false;
    	if($userId > 0 && $amount > 0){
    		$this->load->model('user_model');
    		$opreation = '+';
    		$remark = '推荐人订单提成';
    		switch($level){
    			case 1 :
    				$remark .= '(一级)';
    			break;
    			case 2 :
    				$remark .= '(二级)';
    				break;
    			case 3 :
    				$remark .= '(三级)';
    			break;
    			case 0:
    				$remark = "推荐人首次下单提成";
    			break;
    		}
    		$result = $this->user_model->updateUserCountBalance($userId, $opreation , $amount)
    		&& $this->user_model->addUserCountRecord($userId, $amount, $opreation , 0 , $orderNum ,$remark);
    	}
    	return $result;
    }
    /**
     * 发放商户推荐提成
     * @param unknown $userId
     * @param unknown $amount
     * @param unknown $orderNum
     * @param unknown $level
     */
    private function handedOutShopCommission($shopId , $amount , $orderNum ,$level){
    	$result =false;
    	if($shopId > 0 && $amount > 0){
    		$this->load->model('shop_model');
    		$opreation = '+';
    		$remark = '推荐人订单提成';
    		switch($level){
    			case 1 :
    				$remark .= '(一级)';
    				break;
    			case 2 :
    				$remark .= '(二级)';
    				break;
    			case 3 :
    				$remark .= '(三级)';
    				break;
    			case 0:
    				$remark = "推荐人首次下单提成";
    			break;
    		}
    		$result = $this->shop_model->updateShopCountBalance($shopId, $opreation, $amount)
    		&& $this->shop_model->addShopCountRecord($shopId, $amount, $opreation , 3 , $orderNum ,$remark);
    	}
    	return $result;
    }    
	/**
	 * 判断用户是否首次下单
	 * @param unknown $userId
	 */
    public function isFirstOrder($userId){
    	$result = false;
    	$orderSum = $this->db->select("count(1) as sum")
    						->from('dwf_order')
    						->where(array('user_id'=>$userId , 'status'=>1))
    						->get()
    						->row_array();
    	if($orderSum['sum'] == 1){
    		$result = true;
    	}
    	return $result;
    }
    /**
     * 获取需要交账的订单列表
     * @param unknown $manager_id
     */
    public function getAccountForCommpanyOrderList($manager_id){
        $orderList = array();
        $orderList = $this->db->select('a.id,a.order_num,a.total')
                            ->from('dwf_order as a')
                            ->join('dwf_order_completed as b','a.id=b.order_id','right')
                            ->where(array('a.manager_id'=>$manager_id,'b.account_for_commpany'=>0))
                            ->get()
                            ->result_array();
        $orderListId = array();
        foreach($orderList as $value){
            $orderListId[] = $value['id'];
        }
        if(!empty($orderListId)){
            $orderListPayRecoder = $this->db->select('order_id,money')
                                            ->from('dwf_pay_recorder')
                                            ->where_in('order_id',$orderListId)
                                            ->get()
                                            ->result_array();
            $orderListPayRecoderNew = array();
            foreach($orderListPayRecoder as $value){
                $orderListPayRecoderNew[$value['order_id']] = bcadd($orderListPayRecoderNew[$value['order_id']], $value['money'],2);
            }
            $total = 0;
            foreach($orderList as $key=>$value){
                $orderList[$key]['hasPay'] = isset($orderListPayRecoderNew[$value['id']]) ? $orderListPayRecoderNew[$value['id']] : 0;
                $orderList[$key]['needPay'] = bcsub($value['total'], $orderList[$key]['hasPay'],2);
                if($orderList[$key]['needPay'] < 0){
                    $orderList[$key]['needPay'] = number_format(0,2);
                }
                $total = bcadd($total, $orderList[$key]['needPay'],2);
            }
        }
        return array('orderList'=>$orderList,'total'=>$total);
    }
    /**
     * 更新订单交账状态
     * @param unknown $order_id
     * @return unknown
     */
    public function changeOrderAccountForCommpanyStatus($order_id){
        $result = false;
        $data = array('account_for_commpany'=>1);
        if(is_numeric($order_id)){
            $this->db->where('order_id',$order_id);
        }elseif(is_array($order_id) && !empty($order_id)){
            $this->db->where_in('order_id',$order_id);
        }
        $result = $this->db->update('dwf_order_completed',$data);
        return $result;
    }
    /**
     * 获取没有发放区域经理提成的订单总数
     * @return unknown
     */
    public function getNotAccountForManagerOrderNum(){
        $count = 0;
        $count = $this->db->from('dwf_order_completed')->where('account_for_manager',0)->count_all_results();
        return $count;
    }
    /**
     * 获取没有发放区域经理提成的订单
     * @param number $start
     * @param number $limit
     * @return array
     */
    public function getNotAccountForManagerOrderList($start = 0 , $limit = 0){
        $order_list = array();
        $this->db->select('id,order_id')
        ->from('dwf_order_completed')
        ->where('account_for_manager',0)
        ->order_by('id ASC');
        if($limit != 0){
            $this->db->limit($limit,$start);
        }
        $order_list = $this->db->get()->result_array();
        return $order_list;
    }
    /**
     * 获取没有发放推荐用户提成的订单总数
     * @return unknown
     */
    public function getNotAccountForRecommenderOrderNum(){
    	$count = 0;
    	$count = $this->db->from('dwf_order_completed')->where('account_for_recommender',0)->count_all_results();
    	return $count;
    }
    /**
     * 获取没有发放用户提成的订单
     * @param number $start
     * @param number $limit
     * @return array
     */
    public function getNotAccountForRecommenderOrderList($start = 0 , $limit = 0){
    	$order_list = array();
    	$this->db->select('id,order_id')
    			->from('dwf_order_completed')
    			->where('account_for_recommender',0)
    			->order_by('id ASC');
    	if($limit != 0){
    		$this->db->limit($limit,$start);
    	}
    	$order_list = $this->db->get()->result_array();	
    	return $order_list;
    }
    /**
     * 更新订单提成发放状态
     * @param unknown $order_id
     * @return unknown
     */
    private function updateAccountdForRecommenderOrderStatus($order_id){
    	$result = false;
    	$data = array('account_for_recommender'=>1);
    	$result = $this->db->where('order_id',$order_id)->update('dwf_order_completed',$data);
    	return $result;
    }
    /**
     * 获取没有退还消费金额的取消的订单的总数
     * @return unknown
     */
    public function getNotReturndAmmountOrderNum(){
    	$count = 0;
    	$count = $this->db->from('dwf_order_cancelled')->where('amount_returned',0)->count_all_results();
    	return $count;
    }
    /**
     * 获取没有没有退还消费金额的取消的订单
     * @param number $start
     * @param number $limit
     * @return unknown
     */
    public function getNotReturndAmmountOrderList($start = 0 , $limit = 0){
    	$order_list = array();
    	$this->db->select('id,order_id')
    	->from('dwf_order_cancelled')
    	->where('amount_returned',0)
    	->order_by('id ASC');
    	if($limit != 0){
    		$this->db->limit($limit,$start);
    	}
    	$order_list = $this->db->get()->result_array();
    	return $order_list;
    }
    /**
     * 退还取消的订单的消费金额
     * @param unknown $order_id
     * @return boolean
     */
    public function returnCancelledOrderAmmount($order_id){
    	$result = false;
    	if($order_id > 0){
    		$order_pay_record = $this->getOrderPayRecoder($order_id);
    		if(!empty($order_pay_record)){
    			$this->load->model('pay_model');
    			foreach($order_pay_record as $value){
    				switch ($value['pay_type']) {
    					case 0:
    						$this->pay_model->returnForUserCountBalance($value['user_id'], $value['order_id'] ,$value['money']);
    					break;
    					case 1:
    						$this->pay_model->returnForUserWechat($order_id, $value['money'], $value['money']);
    					break;
    					case 2:
    						$user_coupon_id = $this->getOrderUsedCouponId($order_id);
    						$this->pay_model->returnForUserCoupon($user_coupon_id);
    					break;
    					default:
    						$this->pay_model->returnForUserCountBalance($value['user_id'], $value['order_id'] ,$value['money']);
    					break;
    				}
    			}
    			$result = true;
    		}
    		$this->updateCancelledOrderAmmountReturnStatus($order_id);
    	}
    	return $result;
    }
    /**
     * 获取订单使用的用户优惠券id
     * @param unknown $order_id
     * @return unknown
     */
    public function getOrderUsedCouponId($order_id){
    	$user_coupon_id = $this->db->select('user_coupon_id')
    								->from('dwf_online_coupon_used_log')
    								->where('order_id',$order_id)
    								->get()
    								->row_array();
    	return intval($user_coupon_id['user_coupon_id']);
    }
    /**
     * 更新取消的订单的退款状态
     * @return unknown
     */
    private function updateCancelledOrderAmmountReturnStatus($order_id){
    	$result = false;
    	$data = array('amount_returned'=>1);
    	$result = $this->db->where('order_id',$order_id)->update('dwf_order_cancelled',$data);
    	return $result;
    }
    /**
     * 获取订单在线支付订单号信息
     * @param unknown $order_id
     * @param unknown $pay_way
     * @return unknown
     */
    public function getOrderOnlinePayNo($order_id , $pay_way){
        $orderOnlinePayNoInfo = $this->db->where(array('order_id'=>$order_id,'pay_way'=>$pay_way))->get('dwf_order_online_pay_no')->row_array();
        return $orderOnlinePayNoInfo;
    }
    /**
     * 获取在线支付订单未支付的订单总数
     * @return unknown
     */
    public function getOrderOnlineNotPayNum(){
        $count = 0;
        $count = $this->db->from('dwf_order')->where(array('`order_time` >='=>'2017-07-02 00:00:00','status'=>4))->count_all_results();
        return $count;
    }
    /**
     * 获取在线支付订单未支付的订单
     * @param number $start
     * @param number $limit
     * @return unknown
     */
    public function getOrderOnlineNotPay($start = 0 , $limit = 0){
    	$order_list = array();
    	$this->db->select('a.`id`,a.`order_num`,a.`total`,a.`user_id`,a.`order_time`,b.`add_time` AS send_time')
    	->from('dwf_order AS a')
    	->join('dwf_order_online_not_pay_message_send AS b','a.id = b.order_id','left')
    	->where(array('a.order_time >='=>'2017-07-02 00:00:00','a.status'=>4))
    	->order_by('a.id ASC');
    	if($limit != 0){
    		$this->db->limit($limit,$start);
    	}
    	$order_list = $this->db->get()->result_array();
    	$order_ids = array();
    	foreach($order_list as $value){
    	    $order_ids[] = $value['id'];
    	}
    	if(!empty($order_ids)){
    	    $order_pay_recoder = $this->getOrderPayRecoder($order_ids);
    	}
    	$order_has_pay = array();
    	foreach($order_pay_recoder as $value){
    	    $order_has_pay[$value['order_id']] = bcadd($order_has_pay[$value['order_id']], $value['money'], 2);
    	}
    	foreach($order_list as $key=>$value){
    	    $order_list[$key]['hasPay'] = 0;
    	    if(isset($order_has_pay[$value['id']])){
    	        $order_list[$key]['hasPay'] = $order_has_pay[$value['id']];
    	    }
    	    $order_list[$key]['needPay'] = bcsub($value['total'], $order_list[$key]['hasPay'] , 2);
    	}
    	return $order_list;
    }
    /**
     * 添加未支付订单发送付款提醒消息记录
     * @param unknown $orderId
     * @return boolean
     */
    public function addOrderOnlineNotPayNotifyLog($orderId){
        $result = false;
        if($orderId > 0){
            $data = array(
                'order_id'=>$orderId,
                'add_time'=>date('Y-m-d H:i:s')
            );
            $result = $this->db->insert('dwf_order_online_not_pay_message_send',$data);
        }
        return $result;
    }
    /**
     * 发放区域经理提成
     * @param unknown $orderId
     */
    public function handedOutManagerCommission($orderId){
        if(is_numeric($orderId) && $orderId > 0){
            $orderProduct = $this->db->select(' a.`area_proportion` , a.`product_num` , b.`manager_id`')
                                    ->from('`dwf_order_product`  AS a')
                                    ->join('`dwf_order` AS b','a.order_id=b.id','left')
                                    ->where('a.order_id',$orderId)
                                    ->get()->result_array();
            $fee = 0;
            $manager_id = 0;
            foreach($orderProduct as $value){
                $manager_id = $value['manager_id'];
                $fee = bcadd($fee, bcmul($value['area_proportion'],$value['product_num'],2),2);
            }
            if($fee < 4){
                $fee = 4;
            }
            if($manager_id != 0 && $fee != 0){
                $this->load->model('manager_model');
                $opreation = '+';
                $amount = $fee;
                $managerId = $manager_id;
                $remark = '配送提成';
                $this->manager_model->updateManagerCountBalance($managerId, $opreation, $amount)
                && $this->manager_model->addManagerCountRecord($managerId, $amount, $opreation, $orderId,$remark)
                ;
            }
        }
        $this->updateAccountdForManagerOrderStatus($orderId);
    }
    /**
     * 更新订单提成发放状态
     * @param unknown $order_id
     * @return unknown
     */
    private function updateAccountdForManagerOrderStatus($order_id){
        $result = false;
        $data = array('account_for_manager'=>1);
        $result = $this->db->where('order_id',$order_id)->update('dwf_order_completed',$data);
        return $result;
    }
}